package com.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.example.common.exception.BusinessException;
import com.example.common.exception.UnauthorizedException;
import com.example.common.utils.JwtUtils;
import com.example.common.utils.RedisUtils;
import com.example.user.api.LoginDTO;
import com.example.user.api.LoginResponseDTO;
import com.example.user.entity.User;
import com.example.user.service.AuthService;
import com.example.user.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 登入模块
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private UserService userService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisUtils redisUtils;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public LoginResponseDTO login(LoginDTO loginDTO) {
        // 1. 查询用户
        User user = userService.getOne(new QueryWrapper<User>()
                .eq("username", loginDTO.getUsername()));
        if (user == null) {
            throw new UnauthorizedException("查询-用户名或密码错误");
        }

        // 2. 验证密码（注册时需用BCrypt加密存储）
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new UnauthorizedException("验证密码-用户名或密码错误");
        }

        // 3. 生成JWT令牌
        String token = jwtUtils.generateToken(user.getId(), user.getUsername());

        // 4. 令牌存入Redis（过期时间与JWT一致）
        redisUtils.setToken(token, user.getId(), 3600000); // 1小时

        // 5. 构建响应
        LoginResponseDTO response = new LoginResponseDTO();
        response.setToken(token);
        response.setUserId(user.getId());
        response.setUsername(user.getUsername());
        return response;
    }

    @Override
    public void logout(String token) {
        redisUtils.deleteToken(token);
    }
}
